<template>
	<view class="inline-flex item-center py-2 radius-15 bg-default text-color-regular">
		<view class="pr-10 pl-15" :class="subtractDisabled?'c9':''" @click="onSubtract">-</view>
		<input class="px-2 text-center w-40" type="number" inputmode="numeric" :disabled="disabled" v-model="currentValue" controlled @blur="onBlur" @input="onInput" />
		<view class="pr-15 pl-10" :class="addDisabled?'c9':''" @click="onAdd">+</view>
	</view>
</template>

<script setup>
	import {
		computed,
		nextTick,
		ref,
		unref,
		watch,
	} from 'vue'

	const props = defineProps({
		min: {
			type: Number,
			default: 0
		},
		max: {
			type: Number,
			default: 99999
		},
		disabled: {
			type: Boolean,
			default: false
		},
		step: {
			type: Number,
			default: 1
		},
		value: {
			type: Number,
			default: 0
		}
	})

	const emits = defineEmits(['change'])

	const currentValue = ref(props.value)
	
	watch(() => props.value, (val) => {
		console.log('watch ', currentValue.value, val)
		currentValue.value = val
	})
	
	const subtractDisabled = computed(() => {
		return props.disabled || currentValue.value <= props.min
	})
	
	const addDisabled = computed(() => {
		return props.disabled || currentValue.value >= props.max
	})

	const onSubtract = () => {
		if (subtractDisabled.value) return
		if (currentValue.value > props.min) {
			if (currentValue.value - props.step >= props.min) {
				currentValue.value = currentValue.value - props.step
				emits('change', unref(currentValue.value))
			}
		}
	}

	const onAdd = () => {
		if (addDisabled.value) return
		if (currentValue.value < props.max) {
			if (currentValue.value + props.step <= props.max) {
				currentValue.value = currentValue.value + props.step
				emits('change', unref(currentValue.value))
			}
		}
	}
	
	const onBlur = (e) => {
		console.log('onBlur', e, currentValue.value)
	}

	const onInput = ({
		detail
	}) => {
		const num = +detail.value
		// currentValue.value = num
		console.log('input', detail, currentValue.value, props.min, props.max, num)
		if (num < props.min) {
			nextTick(() => {
				currentValue.value = props.min
				console.log('111', currentValue.value)
				// emits('change', unref(currentValue.value))
			})
		} else if (num > props.max) {
			nextTick(() => {
				currentValue.value = props.max
				console.log('222', currentValue.value)
				emits('change', unref(currentValue.value))
			})
			
		} else {
			currentValue.value = num + ''
			console.log('333', currentValue.value)
			emits('change', unref(currentValue.value))
		}
	}
</script>
